import { Injectable } from '@nestjs/common'
import { createDto, updateDto, createWxDto } from './dto/user.dto'
import { InjectRepository } from '@nestjs/typeorm'
import { UserEntity } from 'src/entities/user.entity'
import { Repository } from 'typeorm'
import to from 'await-to-js'
import { JwtService } from '@nestjs/jwt'
import { IPayload } from 'src/common/interfaces'

@Injectable()
export class AuthService {
  constructor(
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
    private readonly jwtService: JwtService,
  ) {}
  async register(body: createWxDto): Promise<[Error, UserEntity]>
  async register(body: createDto): Promise<[Error, UserEntity]>
  async register(body): Promise<any> {
    const user = await this.userRepository.create(body)
    const [err] = await to(this.userRepository.insert(user))
    return [err, user]
  }
  async login(user: UserEntity): Promise<any> {
    const payload: IPayload = { id: user.id }
    const res = await this.userRepository.findOne({
      where: { id: payload.id },
    })
    return {
      token: this.jwtService.sign(payload, {
        expiresIn: process.env.expiresIn,
      }),
      user: res,
    }
  }
  async validateUser(username: string, password: string): Promise<UserEntity> {
    return await this.userRepository
      .createQueryBuilder('user')
      .addSelect('user.password')
      .where('user.username = :username', { username })
      .getOne()
  }

  async findOne(payload: IPayload): Promise<UserEntity> {
    var res = await this.userRepository.findOne({
      where: { id: payload.id },
    })
    return res
  }

  async findOneByMap(Map: object): Promise<UserEntity | null> {
    var res = await this.userRepository.findOne({
      where: Map,
    })
    return res
  }

  async findUser(user: UserEntity): Promise<UserEntity> {
    var res = await this.userRepository.findOne(user.id)
    return res
  }

  async update(body: updateDto, user: UserEntity): Promise<[Error, any]> {
    let res
    try {
      // var tar = await this.userRepository.findOne(user.id)
      // tar.nickName = body.nickName
      // tar.avator = body.avator
      // tar.phone = body.phone
      // res = await this.userRepository.save(tar)
      res = await this.userRepository.update(user.id, body)
    } catch (error) {
      return [error, null]
    }
    return [null, res]
  }
}
